package edu.neu.swc.cloud.controller;

import com.alibaba.fastjson.JSON;
import edu.neu.swc.cloud.domain.Product;
import edu.neu.swc.cloud.domain.ProductCata;
import edu.neu.swc.cloud.domain.QueryInfo;
import edu.neu.swc.cloud.service.CategoryService;
import edu.neu.swc.cloud.service.ProductService;
import edu.neu.swc.cloud.util.UuidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/product")
public class ProductController {

    @Autowired
    ProductService productService;

    @Autowired
    CategoryService categoryService;


    @RequestMapping("/allProductTypeList")
    public String allProductTypeList(){
        List<ProductCata> productTypeList = categoryService.findAllPro();
        HashMap<String,Object> res = new HashMap<>();
        res.put("data",productTypeList);
        System.out.println(productTypeList);
        return JSON.toJSONString(res);
    }

    @RequestMapping("/productList")
    public String productList(QueryInfo queryInfo){
        int numbers = productService.getProductCounts("%"+queryInfo.getQuery()+"%");
        int pageStart = (queryInfo.getPageNum()-1)*queryInfo.getPageSize();
        List<Product> productList = productService.findProductByQuery("%"+queryInfo.getQuery()+"%",pageStart,queryInfo.getPageSize());
        HashMap<String,Object> res = new HashMap<>();
        res.put("numbers",numbers);
        res.put("data",productList);
        System.out.println("总条数："+numbers);
        System.out.println(productList);
        return JSON.toJSONString(res);
    }

    @RequestMapping("/addProduct")
    public String addProduct(@RequestBody Product product){
        product.setPro_code(UuidUtil.getProCode());
        productService.addProduct(product);
        return "success";
    }

    @RequestMapping("/getUpdate")
    public String getUpdate(int id){
        Product product = productService.findProById(id);
        return JSON.toJSONString(product);
    }

    @RequestMapping("/editProduct")
    public String editProduct(@RequestBody Product product){
        productService.updatePro(product);
        return "success";
    }

    @RequestMapping("/deleteProduct")
    public String deleteProduct(int id){
        productService.deleteProById(id);
        return "success";
    }

    @RequestMapping("/allProductList")
    public String allProductList(){
        List<Product> productList = productService.findAll();
        HashMap<String,Object> res = new HashMap<>();
        res.put("data",productList);
        System.out.println(productList);
        return JSON.toJSONString(res);
    }
}
